package com.wutma.friend.service.user.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.wutma.api.domain.RemoteJudgeService;
import com.wutma.api.domain.dto.JudgeSubmitDTO;
import com.wutma.api.domain.vo.UserExeResult;
import com.wutma.common.core.constants.Constants;
import com.wutma.common.core.domain.R;
import com.wutma.common.core.enums.ProgramType;
import com.wutma.common.core.enums.QuestionResType;
import com.wutma.common.core.enums.ResultCode;
import com.wutma.common.core.utils.ThreadLocalUtil;
import com.wutma.common.security.exception.ServiceException;
import com.wutma.friend.domain.exam.dto.UserSubmitDTO;
import com.wutma.friend.domain.question.entity.Question;
import com.wutma.friend.domain.question.entity.QuestionCase;
import com.wutma.friend.domain.question.vo.QuestionESVO;
import com.wutma.api.domain.vo.UserQuestionResultVO;
import com.wutma.friend.domain.user.entity.UserSubmit;
import com.wutma.friend.manager.QuestionEsManager;
import com.wutma.friend.mapper.question.QuestionMapper;
import com.wutma.friend.mapper.user.UserSubmitMapper;
import com.wutma.friend.rabbitmq.JudgeProducer;
import com.wutma.friend.service.user.IUserQuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserQuestionServiceImpl implements IUserQuestionService {

    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private QuestionEsManager questionEsManager;

    @Autowired
    private RemoteJudgeService remoteJudgeService;

    @Autowired
    private JudgeProducer judgeProducer;

    @Autowired
    private UserSubmitMapper userSubmitMapper;

    @Override
    public R<UserQuestionResultVO> submit(UserSubmitDTO userSubmitDTO) {

        Integer programType = userSubmitDTO.getProgramType();
        if (ProgramType.JAVA.getValue().equals(programType)) {
            // 执行Java语言逻辑
            JudgeSubmitDTO judgeSubmitDTO = assembleJudgeSubmitDTO(userSubmitDTO);
            if (judgeSubmitDTO == null) {
                throw new ServiceException(ResultCode.FAILED);
            }
            // 进行远程调用
            return remoteJudgeService.doJudgeJavaCode(judgeSubmitDTO);
        }
        throw new ServiceException(ResultCode.FAILED_NOT_SUPPORT_PROGRAM);
    }

    @Override
    public boolean rabbitSubmit(UserSubmitDTO userSubmitDTO) {
        Integer programType = userSubmitDTO.getProgramType();
        if (ProgramType.JAVA.getValue().equals(programType)) {
            // 执行Java语言逻辑
            JudgeSubmitDTO judgeSubmitDTO = assembleJudgeSubmitDTO(userSubmitDTO);
            // 使用mq生产消息并发送
            judgeProducer.produceMsg(judgeSubmitDTO);
            return true;
        }
        throw new ServiceException(ResultCode.FAILED_NOT_SUPPORT_PROGRAM);
    }

    @Override
    public UserQuestionResultVO exeResult(Long questionId, Long examId, String currentTime) {

        Long userId = ThreadLocalUtil.get(Constants.USER_ID, Long.class);
        UserSubmit userSubmit = userSubmitMapper.selectCurrentExeResult(questionId, examId, userId, currentTime);
        UserQuestionResultVO userQuestionResultVO = new UserQuestionResultVO();
        if (userSubmit == null) {
            userQuestionResultVO.setPass(QuestionResType.IN_JUDGE.getValue());
        }
        else {
            userQuestionResultVO.setPass(userSubmit.getPass());
            userQuestionResultVO.setExeMessage(userSubmit.getExeMessage());
            if (StrUtil.isNotEmpty(userSubmit.getCaseJudgeRes())) {
                userQuestionResultVO.setUserExeResultList(JSON.parseArray(userSubmit.getCaseJudgeRes(), UserExeResult.class));
            }
        }
        return userQuestionResultVO;
    }

    private JudgeSubmitDTO assembleJudgeSubmitDTO(UserSubmitDTO userSubmitDTO) {

        JudgeSubmitDTO judgeSubmitDTO = new JudgeSubmitDTO();
        QuestionESVO questionEsVO = questionEsManager.getQuestionEsVO(userSubmitDTO.getQuestionId());
        if (questionEsVO != null) {
            BeanUtil.copyProperties(questionEsVO, judgeSubmitDTO);
        }
        else {
            // ES中查询不到，则从数据库中获取
            Question question = questionMapper.selectById(userSubmitDTO.getQuestionId());
            if (question == null) {
                return null;
            }
            BeanUtil.copyProperties(question, judgeSubmitDTO);
            // 刷新ES
            questionEsManager.refreshES();
        }
        judgeSubmitDTO.setUserId(ThreadLocalUtil.get(Constants.USER_ID, Long.class));
        judgeSubmitDTO.setExamId(userSubmitDTO.getExamId());
        judgeSubmitDTO.setProgramType(userSubmitDTO.getProgramType());
        judgeSubmitDTO.setUserCode(codeConnect(userSubmitDTO.getUserCode(), questionEsVO.getMainFuc()));
        List<QuestionCase> questionCaseList = JSONUtil.toList(questionEsVO.getQuestionCase(), QuestionCase.class);
        List<String> inputList = questionCaseList.stream().map(QuestionCase::getInput).toList();
        judgeSubmitDTO.setInputList(inputList);
        List<String> outPutList = questionCaseList.stream().map(QuestionCase::getOutput).toList();
        judgeSubmitDTO.setOutputList(outPutList);
        return judgeSubmitDTO;
    }

    private String codeConnect(String userCode, String mainFunc) {
        String targetCharacter = "}";
        int targetLastIndex = userCode.lastIndexOf(targetCharacter);
        if (targetLastIndex != -1) {
            return userCode.substring(0, targetLastIndex) + "\n" + mainFunc + "\n" + userCode.substring(targetLastIndex);
        }
        throw new ServiceException(ResultCode.FAILED);
    }



}
